using Abc.Core.Entities;

using Furion;
using Furion.DatabaseAccessor;

using Microsoft.EntityFrameworkCore;

using System;

using Tool;

namespace Abc.Core.EntitiesChangedListeners
{
    public class EntitiesChangedListeners :
IEntityChangedListener<DataConfig>
, IEntityChangedListener<Menu>
, IEntityChangedListener<Role>
, IEntityChangedListener<MenuPermission>
, IEntityChangedListener<RolePermission>
, IEntityChangedListener<Permission>
, IEntityChangedListener<User>
    {
        // DataConfig
        public void OnChanged(DataConfig newEntity, DataConfig oldEntity, DbContext dbContext, Type dbContextLocator, EntityState state)
        {
            App.GetService<IRepository<DataConfig>>().AsEnumerable().SetMemoryCache(CacheConst.DataConfig);
        }

        // Menu
        public void OnChanged(Menu newEntity, Menu oldEntity, DbContext dbContext, Type dbContextLocator, EntityState state)
        {
            App.GetService<IRepository<Menu>>().AsEnumerable().SetMemoryCache(CacheConst.Menu);
        }

        // Role
        public void OnChanged(Role newEntity, Role oldEntity, DbContext dbContext, Type dbContextLocator, EntityState state)
        {
            App.GetService<IRepository<Role>>().AsEnumerable().SetMemoryCache(CacheConst.Role);
        }

        // Permission
        public void OnChanged(Permission newEntity, Permission oldEntity, DbContext dbContext, Type dbContextLocator, EntityState state)
        {
            App.GetService<IRepository<Permission>>().AsEnumerable().SetMemoryCache(CacheConst.Permission);
            //Permission 缓存了  Include(o=>o.Menus) 所以有变化需要更新缓存
            App.GetService<IRepository<Menu>>().AsEnumerable().SetMemoryCache(CacheConst.Menu);
            //Role 缓存了  Include(o=>o.Permissions) 所以有变化需要更新缓存
            App.GetService<IRepository<Role>>().AsEnumerable().SetMemoryCache(CacheConst.Role);
        }

        // MenuPermission
        public void OnChanged(MenuPermission newEntity, MenuPermission oldEntity, DbContext dbContext, Type dbContextLocator, EntityState state)
        {
            //因为Menu 缓存了 Include(o=>o.Permissions) 所以有变化需要更新缓存
            App.GetService<IRepository<Menu>>().AsEnumerable().SetMemoryCache(CacheConst.Menu);
        }

        // RolePermission
        public void OnChanged(RolePermission newEntity, RolePermission oldEntity, DbContext dbContext, Type dbContextLocator, EntityState state)
        {
            App.GetService<IRepository<Role>>().AsEnumerable().SetMemoryCache(CacheConst.Role);
            App.GetService<IRepository<Permission>>().AsEnumerable().SetMemoryCache(CacheConst.Permission);
        }

        public async void OnChanged(User newEntity, User oldEntity, DbContext dbContext, Type dbContextLocator, EntityState state)
        {
            //刷新登陆管理用户缓存
            await App.GetService<ICacheService>().RefreshLoginAdminUserCache(oldEntity.Id);
        }
    }
}